package com.tunnel.home.common;

import java.util.List;
import java.util.Map;

import org.axe.util.StringUtil;

import io.lettuce.core.api.StatefulRedisConnection;
import io.lettuce.core.api.sync.RedisCommands;

public class RedisUtil {

	private static StatefulRedisConnection<String, String> connection;

	public static void setConnection(StatefulRedisConnection<String, String> connection) {
		RedisUtil.connection = connection;
	}

	public static void setMap(String key, Map<String, String> map, int timeOutSeconds) {
		if(connection != null){
			RedisCommands<String,String> commands = connection.sync();// <4> 创建同步命令
			commands.hmset(key, map);
			commands.expire(key, timeOutSeconds);
		}
	}

	public static Map<String, String> getMap(String key) {
		RedisCommands<String, String> commands = connection.sync();// <4> 创建同步命令
		Map<String, String> map = commands.hgetall(key);
		return map;
	}

	public static void deleteElement(String key) {
		RedisCommands<String, String> commands = connection.sync();// <4> 创建同步命令
		commands.del(key);
	}

	public static void setKeyValue(String key, String value, int timeOutSeconds) {
		RedisCommands<String, String> commands = connection.sync();// <4> 创建同步命令
		commands.set(key, value);
		commands.expire(key, timeOutSeconds);
	}

	public static String getString(String key) {
		RedisCommands<String, String> commands = connection.sync();// <4> 创建同步命令
		return commands.get(key);
	}

	public static String getAndDelString(String key) {
		String val = getString(key);
		if (StringUtil.isNotEmpty(val)) {
			deleteElement(key);
		}
		return val;
	}


	public static List<String> getKeys(String pattern){
		RedisCommands<String, String> commands = connection.sync();// <4> 创建同步命令
		return commands.keys(pattern);
	}
	
	public static Long incr(String key){
		RedisCommands<String,String> commands = connection.sync();
		return commands.incr(key);
	}

	public static void setExpire(String key, int timeOutSeconds){
		RedisCommands<String,String> commands = connection.sync();
		commands.expire(key, timeOutSeconds);
	}
}
